package com.dream.auth.security;

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

@Component
public class CustomPasswordEncoder implements PasswordEncoder {

    private final BCryptPasswordEncoder bcryptEncoder = new BCryptPasswordEncoder();

    @Override
    public String encode(CharSequence rawPassword) {
        return bcryptEncoder.encode(rawPassword);
    }

    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {
        // 如果密码为空，直接返回false
        if (encodedPassword == null) {
            return false;
        }

        // 根据密码前缀判断加密方式
        if (encodedPassword.startsWith("{bcrypt}")) {
            return bcryptEncoder.matches(rawPassword, encodedPassword.substring(8));
        } else if (encodedPassword.startsWith("{noop}")) {
            return rawPassword.toString().equals(encodedPassword.substring(6));
        } else if (encodedPassword.startsWith("{md5}")) {
            return encodeMD5(rawPassword.toString()).equals(encodedPassword.substring(5));
        } else {
            // 默认使用BCrypt
            return bcryptEncoder.matches(rawPassword, encodedPassword);
        }
    }

    private String encodeMD5(String password) {
        try {
            java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
            byte[] array = md.digest(password.getBytes());
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < array.length; ++i) {
                sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1,3));
            }
            return sb.toString();
        } catch (java.security.NoSuchAlgorithmException e) {
            throw new RuntimeException("MD5加密失败", e);
        }
    }
} 